//Code for Django CSRF protection
// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function setupCSRF() {
    var csrftoken = getCookie('csrftoken');
    $("input[name='csrfmiddlewaretoken']").val(csrftoken);
}

//get html snippet by ajax
function get_html_snippet(filename, callback) {
    url = '/forum/html/' + filename + '/';
    return $.get(
        url, 
        function(result) {
            callback(result);
        }
    );
}

//Open or close the relevant add-a-new-push form
$(".push_link").click(function(event) {
    event.preventDefault();
    $(this).parent().siblings("form:first").slideToggle(100);
});

//Submit the push form using Ajax
$(".push_input").submit(function(event){
    event.preventDefault();
    var this_form = $(this)

    $.post(
        //url: action value
        $(this).attr("action"),
        $(this).serialize(),
        function(result){
            this_form.siblings(".post_push")
                .fadeOut(400, function() {
                    $(this).html(result);
                })
                .fadeIn(400)
            .end().slideToggle(100)[0].reset();
            setupCSRF();
        }
    )
    .fail(function() {
        popdiv.setlocal("推文失败", "", "提交推文失败，请重试或检查网络.");
    });
});

//Show a menu for operating this post
$(".post").mouseover(function(){
    $(this).children(".post_buttons").css('visibility', 'visible');
}).mouseout(function() {
    $(this).children(".post_buttons").css('visibility', 'hidden');
})

//Handle the function links at the top of board manage page
$("#mng_board_addbd").on('click', function(event) {
    event.preventDefault();
    $("#mng_add_board_category").hide();
    $("#mng_add_board").toggle();
})

$("#mng_board_addbdct").on('click', function(event) {
    event.preventDefault();
    $("#mng_add_board").hide();
    $("#mng_add_board_category").toggle();
})

//Select all/none for user part in manage backend
$("#mng_users_selectall").change(function() {
    $("input:checkbox", $("tbody")).prop("checked", this.checked);
});

$("input:checkbox", $("tbody")).change(function() {
    if(!this.checked) {
        $("#mng_users_selectall").prop("checked", this.checked);
    }
})

//Behaviors of adduser link(#mng_users_link_add) in user manage page
$("#mng_users_link_add").click(function(event) {
    event.preventDefault();
    $("#alertdiv_title").html("新增用户").parent().parent().show();
});


//Behaviors of input widget when onblur/onfocus
function reg_log_form_input_onblur(input) {
    if(input.val() == '') {
        input.addClass("log_reg_input_init");
        input.val(input.attr('value'));
        return false;
    };
    return true;
};

function reg_log_form_input_onfocus(input, ispassword) {
    if(ispassword) {
        input.attr("type", "password");
    };

    input.removeClass("log_reg_input_init");
    if(input.val() == input.attr("value")) {
        input.val("");
    };
};

$(".log_reg_input").blur(function() {
    reg_log_form_input_onblur($(this));
});

$(".log_reg_input").focus(function() {
    reg_log_form_input_onfocus($(this, false));
});

$(".log_reg_pwd").blur(function() {
    if(!reg_log_form_input_onblur($(this))) {
        $(this).attr("type", "text");
    };
});

$(".log_reg_pwd").focus(function() {
    reg_log_form_input_onfocus($(this), true);
});

//Pop layer bahavior - Start
var alertdiv = $("#alertdiv");
var alertdiv_close = $("#alertdiv_close");
var alertdiv_title = $("#alertdiv_title");
var alertdiv_warning = $("#alertdiv_warning");
var alertdiv_loading = $("#alertdiv_loading");
var alertdiv_main = $("#alertdiv_main");

//make popdiv dragable
var _moving = false;
var originX, originY;
var mouseOX, mouseOY;

$("#alertdiv_top").mousedown(function(event) {
    _moving = true;

    originX = alertdiv.offset().left;
    originY = alertdiv.offset().top;

    mouseOX = event.pageX;
    mouseOY = event.pageY;
    
}).mouseup(function() {
    _moving = false;
});
$(document).mousemove(function(event) {
    if(_moving) {
        var offsetX = event.pageX - mouseOX;
        var offsetY = event.pageY - mouseOY;
        
        var newX = originX + offsetX;
        var newY = originY + offsetY;

        alertdiv.offset({top: newY, left: newX});
    }
});
$(window).resize(function() {
    alertdiv.css({
        top: $(window).height()*0.4 - alertdiv.outerHeight()*0.5,
        left: $(window).width()*0.5 - alertdiv.outerWidth()*0.5
    });
});
$(window).resize();

alertdiv_close.click(function() {
    alertdiv.hide();
    $(window).resize();
});

var popdiv = new Object();
popdiv.title = function(t) {
    if(typeof t === undefined) {
        return alertdiv_title.html();
    } else {
        alertdiv_title.html(t);
        return this;
    }
}
popdiv.getjquery = function(o) {
    switch(o) {
        case 'title':
            return alertdiv_title;
        case 'warning':
            return alertdiv_warning;
        case 'main':
            return alertdiv_main;
        default:
            return alertdiv;
    }
}
popdiv.warning = function(w) {
    if(w === undefined) {
        return alertdiv_warning.html();
    } else if(w == "") {
        alertdiv_warning.html(w).hide();
        return this;
    } else {
        alertdiv_warning.html(w).show();
        return this;
    }
}
popdiv.show = function() {
    alertdiv.show();
    return this;
}
popdiv.hide = function() {
    alertdiv.hide();
    return this;
}
popdiv.set = function(t, f, w, display) {
    this.title(t);
    alertdiv_main.html("");
    alertdiv_warning.hide();
    alertdiv_loading.show();
    if(display === undefined || display) {
        alertdiv_close.click();
        this.show();
    } else {
        this.hide();
    }
    if(f) {
        return get_html_snippet(f, function(result) {
            alertdiv_loading.hide();
            alertdiv_main.html(result);
        });
    }
    if(w === undefined) {
        this.warning('');
    } else {
        this.warning(w);
    }
}
popdiv.setlocal = function(t, s, w, display) {
    this.title(t);
    alertdiv_main.html("");
    if(w === undefined) {
        this.warning('');
    } else {
        this.warning(w);
    }
    if(display === undefined || display) {
        this.show();
    } else {
        this.hide();
    }
    alertdiv_main.html(s);
}
//Pop layer bahavior - End

//message delete link behavior
$(".manage_message_list_dellink").click(function(event) {
    event.preventDefault();
    var current_line = $(this).parent().parent();
    var del_link = $(this).attr("href");
    var codename = $(this).parent().siblings(".manage_message_list_name").html();
    
    var title = "请再次确认管理员密码";
    var default_warning = "你将要删除代号为<em></em>的提示信息!";
    popdiv.set(title, 'confirm_admin_pass', default_warning).done(function() {
        popdiv.getjquery('warning').find("em").html(codename);
        $("#admin_pass_confirm_form").submit(function(event) {
            event.preventDefault();
            $.post(
                del_link, 
                {
                    username: "admin", 
                    password: $("#admin_pass_confirm_form input[name='password']").val(), 
                    csrfmiddlewaretoken: getCookie('csrftoken')
                }, 
                function(result) {
                    if(result == "0") {
                        popdiv.hide();
                        current_line.slideUp().remove();
                    } else if(result == "1") {
                        popdiv.warning("管理员密码有错，请重新输入.");
                    } else if(result == "2") {
                        popdiv.warning("发生未知错误，请重试或联系管理员.");
                    } else {
                        popdiv.warning("您可能未以管理员身份登陆.");
                    }
                }
            )
            .fail(function() {
                popdiv.warning("提交请求出错，请重试.");
            });
        });
    });
});

//users add link behavior
$("#mng_users_link_add").click(function(event) {
    event.preventDefault();
    var title = "增加新用户";
    var url = $(this).attr("href");
    popdiv.set(title, 'new_user_form').done(function() {
        $("#manage_users_addform").submit(function(event) {
            event.preventDefault();
            $.post(
            url,
            {
                username: $("#mng_users_optform_username").val(), 
                password: $("#mng_users_optform_password").val(), 
                email: $("#mng_users_optform_email").val(), 
                csrfmiddlewaretoken: getCookie('csrftoken')
            }, 
            function(result) {
                if(result == "0") {
                    window.location.reload();
                } else if(result == '1') {
                    popdiv.warning("发生错误，请检查输入");
                } else if(result == '2') {
                    popdiv.warning("验证失败，请检查输入");
                }
            })
            .fail(function() {
                popdiv.warning("提交请求出错，请重试.");
            });
        });
    });
});

//users delete link behavior
$("#manage_users_del").click(function(event) {
    event.preventDefault();
    var title = "再次确认管理员密码";
    var html_snippet_name = "delete_user_form";
    var url = $(this).attr("href");
    popdiv.set(title, html_snippet_name, "用户信息被删除后不能恢复!").done(function(event) {
        $("#admin_pass_confirm_form").submit(function(event) {
            event.preventDefault();
            var tobe_deleted = $("#mng_users_maintb input[name='selected_items']:checked");
            var delete_relate = $("#admin_pass_confirm_form input[name='delete_relate']:checked").length > 0 ? 1 : 0;
            if(tobe_deleted.length > 0) {
                var selected = [];
                tobe_deleted.each(function() {
                    selected.push(parseInt($(this).val()));
                });

                $.post(
                    url, 
                    {
                        delete_relate: delete_relate,
                        selected_items: selected,
                        csrfmiddlewaretoken: getCookie('csrftoken'), 
                        username: 'admin', 
                        password: $("#admin_pass_confirm_form input[name='password']").val()
                    }, 
                    function(result) {
                        if(result == "0") {
                            window.location.reload();
                        } else {
                            popdiv.warning("删除未成功，请检查输入.");
                        }
                    }
                )
                .fail(function() {
                    popdiv.warning("删除未成功，请检查网络或重试.");
                });
            } else {
                popdiv.hide();
            }
        });
    });
});

//behaviors of login links in board exceptions page
$(".board_exceptions_login").click(function(event) {
    event.preventDefault();
    popdiv.set("登陆", "popdiv_login_form").done(function() {
        var login_form = $("#popdiv_login_form");
        login_form.submit(function(event) {
            event.preventDefault();
            var username = login_form.find("#popdiv_login_form_username").val();
            var password = login_form.find("#popdiv_login_form_password").val();
            ajax_login(username, password, function(s) {
                if(s === '0') {
                    window.location.reload();
                } else {
                    popdiv.warning("登陆失败，请检查用户名和密码.");
                }
            })
            .fail(function() {
                popdiv.warning("登陆失败，请重试或检查网络连接.");
            });
        });
    });
});
$(".manage_boards_perm_link").click(function(event) {
    event.preventDefault();
    $(this).parents("tr:first").find(".manage_boards_edit").click();
});
$(".manage_boards_edit").click(function(event) {
    event.preventDefault();
    var url = $(this).attr("href");
    var this_line = $(this).parents("tr:first");
    var this_name = this_line.children(".manage_boards_name").html();
    var this_showname = this_line.children(".manage_boards_showname").html();
    var this_restrict = this_line.children(".manage_boards_restrict").html() == '是' ? 1 : 0;
    var this_perm = this_line.find(".manage_boards_gperm a").attr("href").slice(-6, -1);
    this_perm += this_line.find(".manage_boards_uperm a").attr("href").slice(-6, -1);
    this_perm += this_line.find(".manage_boards_aperm a").attr("href").slice(-6, -1);

    popdiv.set("修改版块设定", "update_board_form").done(function() {
        var this_form = $("#update_board_form");
        this_form.find("input[name='name']").val(this_name);
        this_form.find("input[name='showname']").val(this_showname);
        this_form.find("input[name='restrict']").each(function() {
            if($(this).attr("value") == this_restrict) {
                this.checked = true;
            }
        });
        var checkboxes = this_form.find("input:checkbox"); 
        checkboxes.each(function(index) {
            if(this_perm.charAt(index) == '1') {
                this.checked = true;
            } else {
                this.checked = false;
            }
        });
        this_form.submit(function(event) {
            event.preventDefault();
            var ck_val1 = '', ck_val2 = '', ck_val3 = '';
            checkboxes.each(function(index) {
                if(index < 5) {
                    ck_val1 += this.checked ? "1" : "0";
                } else if(index < 10) {
                    ck_val2 += this.checked ? "1" : "0";
                } else {
                    ck_val3 += this.checked ? "1" : "0";
                }
            });
            this_form.find("input[name='anonymous_perm']").attr('value', ck_val1);
            this_form.find("input[name='user_perm']").attr('value', ck_val2);
            this_form.find("input[name='admin_perm']").attr('value', ck_val3);
            $.post(
                url, 
                this_form.serialize(), 
                function(result) {
                    if(result == '0') {
                        window.location.reload();
                    } else if(result == '1') {
                        popdiv.warning("发生错误，请重试.");
                    } else if(result == '2') {
                        popdiv.warning("登陆失效，请用重新登陆管理账号.");
                    } else {
                        popdiv.warning("发生未知错误，请重试.");
                    }
                    setupCSRF();
                }
            )
            .fail(function() {
                popdiv.warning("提交请求失败，请重试.");
            });
        });
    });
});

//ajax login common part
function ajax_login(username, password, callback) {
    var url = '/forum/u/ajaxlogin/';
    return $.post(
        url, 
        {
            csrfmiddlewaretoken: getCookie('csrftoken'), 
            username: username, 
            password: password
        }, 
        function(result) {
            callback(result);
        }
    );
}

//upload behavior
//click on upload button
$("#post_form_upload_iframe").load(function() {
    var post_form_upload_iframe = $(this).contents();
    post_form_upload_iframe.find("#post_form_start_upload").click(function() {
        //test if there is an attachment(on the server-side, too)
        var upload_form = post_form_upload_iframe.find("#upload_form");
        var post_form_upload_file = post_form_upload_iframe.find("#post_form_upload_file");

        upload_form.submit();

        post_form_upload_file.after(post_form_upload_file.clone().val('')).remove();
    });
});

